<?php

namespace app\http\middleware;

use app\facade\Token;
use think\Db;
use app\models\{User as Users};
use app\facade\Redis;

class Auth
{
    use \traits\controller\Jump;

    public function handle($request, \Closure $next)
    {
        $url = '/' . $request->controller() . '/' . $request->action();
        $url = strtolower($url);
        $verify = config('auth.api');
        if (!in_array($url, $verify) && !$request->header('token')) {
            $this->result(null, 999, '请登录用户');
        }
        $ip = $request->ip();
        $code = $ip;
        if (($request->header('token') && !in_array($url, $verify))) {
            $user_id = Token::get($request->header('token'));
            $user = (new Users())->where('id', $user_id)->find();
            $code = $user_id;
            if (!$user) {
                $this->result(null, 998, '用户账号错误');
            }
            $request->user = $user;
            $request->user_id = $user_id;
        }
        if (($request->header('token') && in_array($url, $verify))) {
            $user_id = Token::get($request->header('token'));
            $user = (new Users())->where('id', $user_id)->find();
            $code = $user_id;
            $request->user = $user;
            $request->user_id = $user_id;
        }
        $postauth = config('auth.postauth') ?? [];
        if ($request->isPost() && !in_array($url, $postauth)) {
            $unique = $url . '_' . $code;
            $frtimes = Redis::get($unique);
            if ($frtimes) {
                $timerds = Redis::ttl($unique);
                $this->result(null, 404, '请' . $timerds . '秒后再试');
            } else {
                Redis::setex($unique, 1, 1);
            }
        }
        return $next($request);
    }
}
